var map = require('../../resource/js/map.js')
var co = require('../../resource/js/common.js')
var app = getApp()
var _this
var pnCount = 1

Page({
    /*页面的初始数据*/
    data: {
        map: '',
        // 当前位置
        nearbyShops: [],
        isShow: true,
        distance: [],
        startScore: [],
        nowAddress: '',
        screenHeight: '',
        sort: [
            { name: '好评优先' },
            { name: '销量最高' },
            { name: '距离最近' }
        ],
        id: '',
        // allSort: false,
        // price: false,
        // rank: false,
        // sortlist: [],
        // pricelist: [],
        // ranklist: ["价格升序", "价格降序", "离我最近"],
        latAndlng: [],
        isShop: false,
        noShopInfo: '',
        priceClick: '',
        minp: '',
        maxp: '',
        allSortClick: '',
        allSortIndex: '',
        // 输入框搜索商家
        searchInfo: '',
        // 触底加载后显示
        isLoad: false,
        noMore: false,
        returnTop: '',
        // 评分星星显示
        score: [],
        star: [],
        // 天气
        Weather: [],
        // 现在温度
        nowC: '',
        image: '',
        //自定义弹窗参数
        setGuestNumShow: 0,
        numArray: [
            [1, 2, 3, 4],
            [5, 6, 7, 8],
            [9, 10, 11, 12],
            [13, 14, 15, 0]
        ],
        // 传递信息
        Biz_ID: '',
        Table_ID: ''
    },
    /*生命周期函数--监听页面加载*/
    onLoad: function (options) {
        _this = this
        // 获取获取设备信息
        var sys = wx.getSystemInfoSync().windowHeight - 203
        this.setData({ screenHeight: sys })
        this.getUserMap()
    },
    // 进入附近商家地图版
    location: function () {
        wx.switchTab({
            url: '/02local/01local/local'
        })
    },
    // 搜索附近商家
    searchInfo: function (e) {
        var info = e.detail.value
        this.setData({ searchInfo: info })
    },
    search: function () {
        var keyword = this.data.searchInfo           //搜索关键字
        var latn = this.data.latAndlng               //获取经纬度
        var param = {
            longitude: latn[0],
            latitude: latn[1],
            keyword: keyword
        }
        _this.data.nearbyShops = []           //清空附近商家数组
        this.getNearByShop(param, latn[0], latn[1])
        //   this.setData({ searchInfo: '' })
    },
    // 上拉加载更多
    getMoreNearByShop: function (e) {
        pnCount++
        // console.log("【获取更多数据】===",e)
        var latn = this.data.latAndlng
        var index = e.currentTarget.dataset.index
        var param = {
            longitude: latn[0],
            latitude: latn[1],
            pageNo: pnCount,
        }
        //全部分类点击 
        if (this.data.priceClick == "1") {
            param.Category_ID = index
            param.Biz_MinPrice = this.data.minp
            param.Biz_MaxPrice = this.data.maxp
        } else {
            param.Category_ID = index
        }
        this.getNearByShop(param, latn[0], latn[1])
        if (this.data.noMore == true) {
            this.setData({ isLoad: false })
        } else {
            this.setData({ isLoad: true })
        }
    },
    // 排序分类选择
    getRank: function (e) {
        var id = e.currentTarget.id
        this.clearCount()
        // console.log("【获取点击id】===",id,typeof(id))
        // 获取所在位置经纬度
        var list = this.data.latAndlng
        var orderKey = ''
        var orderBy = ''
        if (id == '0') {
            orderKey = 'price'
            orderBy = 'asc'
        } else if (id == '1') {
            orderKey = 'price'
            orderBy = 'desc'
        } else if (id == '2') {
            orderKey = 'distance'
            orderBy = 'asc'
        }
        var param = {
            longitude: list[0],
            latitude: list[1],
            orderKey: orderKey,
            orderBy: orderBy
        }
        this.getNearByShop(param, list[0], list[1])
        this.setData({ rank: false })
    },
    //价格点击默认
    pricetUnlimited: function (e) {
        this.clearCount()
        this.getUserMap()
        this.setData({ price: false, 'sort[1].name': "价格" })
    },
    // 全部分类点击默认
    allSortUnlimited: function () {
        this.clearCount()
        this.getUserMap()
        this.setData({ allSort: false, 'sort[0].name': "全部分类" })
    },
    // 价格点击选择
    priceList: function (e) {
        this.clearCount()
        var minp = parseFloat(e.currentTarget.dataset.start)
        var maxp = parseFloat(e.currentTarget.dataset.end)
        if (e.currentTarget.dataset.end == '') {
            maxp = ''
        }
        // 获取所在位置经纬度
        var list = this.data.latAndlng
        var param = {
            longitude: list[0],
            latitude: list[1],
            Biz_MinPrice: minp,
            Biz_MaxPrice: maxp,
        }
        //判断是否选择了一次分类
        if (this.data.allSortClick == "1") {
            var index = this.data.allSortIndex
            param.Category_ID = index
        }
        this.setData({ priceClick: 1, price: false, 'sort[1].name': "¥" + minp + '~' + maxp, minp: minp, maxp: maxp })
        this.getNearByShop(param, list[0], list[1])
    },
    // 全部分类点击选择
    allSortList: function (e) {
        this.clearCount()
        var index = e.currentTarget.dataset.index
        var name = e.currentTarget.dataset.name
        // 获取所在位置经纬度
        var list = this.data.latAndlng
        var param = {
            longitude: list[0],
            latitude: list[1],
            Category_ID: index,
            pageNo: pnCount,
        }
        if (this.data.priceClick == "1") {
            param.Biz_MinPrice = this.data.minp
            param.Biz_MaxPrice = this.data.maxp
        }
        this.setData({ allSort: false, 'sort[0].name': name, allSortClick: 1, allSortIndex: index })
        this.getNearByShop(param, list[0], list[1])
    },
    // 清空页码及数组
    clearCount() {
        pnCount = 1
        this.setData({ returnTop: 0, nearbyShops: [] })
    },
    // 获取商家行业分类接口
    // getShopingSort() {
    //     if (!co.empty(this.data.sortlist))
    //         return
    //     co.getShareApi('biz/Bmg/getUnionCategory', {}, function (res) {
    //         _this.setData({ sortlist: res.data })
    //     })
    // },
    // 获取分类价格区间
    // getPriceSection() {
    //     if (!co.empty(this.data.pricelist))
    //         return
    //     co.getShareApi("shop/Smg/getPriceSection", {}, function (res) {
    //         _this.setData({ pricelist: res.data })
    //     })
    // },
    // 获取附近商家数据存入nearbyShops
    getNearByShop(param, lng, lat) {
        co.getShareApi('biz/Bmg/getNearbyList', param, function (res) {
            //   console.log("【获取附近商家信息】===",res.code)
            if (res.code == 0) {
                var nbList = _this.data.nearbyShops
                for (var i = 0; i < res.data.length; i++) {
                    nbList.push(res.data[i])
                }
                _this.setData({
                    nearbyShops: nbList,
                    isShop: false
                })
            } else if (res.code == 29300) {
                if (pnCount == 1) {
                    _this.setData({
                        noShopInfo: res.msg,
                        isShop: true
                    })
                } else {
                    _this.setData({
                        isLoad: false,
                        noMore: true
                    })
                }
            }
            for (var i = 0; i < res.data.length; i++) {
                // 根据经纬度计算和商家距离
                _this.getDistance(lng, lat, res.data[i].Biz_PrimaryLng, res.data[i].Biz_PrimaryLat)
                // 评分信息
                _this.showStart(res.data[i].Score)
                // 商家评分
                var list = _this.data.startScore
                list.push(res.data[i].Score)
                _this.setData({ startScore: list })
            }
        })
    },
    // 评分显示星星
    showStart(Score) {
        const LENGTH = 5;
        const CLS_ON = "../../resource/icon/star/on.png"
        const CLS_OFF = "../../resource/icon/star/off.png"
        const CLS_HALF = "../../resource/icon/star/half.png"
        //评分判断
        let starArray = []
        let score = Math.floor(Score * 2) / 2//lpData.data.comment.sRate表示获取当前评分，例如：4.65等
        let hasDecimal = score % 1 !== 0
        let integer = Math.floor(score)
        for (let i = 0; i < integer; i++) {
            starArray.push(CLS_ON)
        }
        if (hasDecimal) {
            starArray.push(CLS_HALF)
        }
        while (starArray.length < LENGTH) {
            starArray.push(CLS_OFF)
        }
        let s = this.data.score
        s.push(Score)
        let a = this.data.star
        a.push(starArray)
        //存入星星数组
        _this.setData({
            score: s,
            star: a
        })
    },
    // 获取用户位置
    getUserMap() {
        // 将获取到的经纬度存入latAndlng
        var lat_lng = _this.data.latAndlng
        var lng = app.Data.p.longitude
        var lat = app.Data.p.latitude
        lat_lng.push(lng)
        lat_lng.push(lat)
        // 调用获取附近商家方法
        var param = {
            longitude: lng,
            latitude: lat,
        }
        _this.getWeather(lat, lng)      //获取天气数据
        _this.getNearByShop(param, lng, lat)
        // 坐标转中文地址
        map.getLocationName(param, function (res) {
            console.log("【获取返回的中文地址】===", res)
            _this.setData({
                nowAddress: res.title,
                latAndlng: lat_lng
            })
        })
    },
    // 根据经纬计算距离
    getDistance(lng1, lat1, lng2, lat2) {
        var radLat1 = lat1 * Math.PI / 180.0;
        var radLat2 = lat2 * Math.PI / 180.0;
        var a = radLat1 - radLat2;
        var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137;
        s = Math.round(s * 100) / 100;
        // return s;
        // console.log("【距离】===", s)
        var list = _this.data.distance
        list.push(s)
        _this.setData({ distance: list })
    },
    bubbleSort: function(arr) {
        for (var i = 0; i < arr.length - 1; i++) {
            for (var j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {//如果前面的数据比后面的大就交换  
                    var temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        return arr;
    },
    // 获取导航条点击的id
    getOrederStatus: function (event) {
        var idx = event.currentTarget.dataset.index
        if (idx == 0) {

        } else if (idx == 1) {

        } else if (idx == 2) {
        }
        this.setData({
            id: idx,
        })
    },
    // 点击隐藏弹窗
    closeModel: function () {
        this.setData({
            allSort: false,
            price: false,
            rank: false,
        })
    },
    // 获取天气
    getWeather: function(latitude, longitude, callback) {
        var ak = "y6KGnZ0tnwKl5uYcGQl7NOAHirGAVr5h"
        var url = "https://api.map.baidu.com/telematics/v3/weather?location=" + longitude + "," + latitude + "&output=json&ak=" + ak
        wx.request({
            url: url,
            success: function (res) {
                console.log("【天气返回信息】===", res.data.results[0].weather_data[0])
                var s = res.data.results[0].weather_data[0].date
                var t = s.split('(实时：')[1].split(')')[0]
                // console.log("【切割字符串】===",t)
                var img = res.data.results[0].weather_data[0].dayPictureUrl
                var i = img.split('day/')[1]
                 console.log("【切割字符串】===",i)
                _this.setData({
                    Weather: res.data.results[0].weather_data[0],
                    nowC: t,
                    image: i
                })
            }
        });
    },
    // 扫描点菜
    scanCode: function () {
        wx.scanCode({
            onlyFromCamera: true,
            success: function (res) {
                var str = res.result
                if (str.indexOf('meal.52g3.cc/index/index/index') > -1) {
                    var strArr = str.split('/')
                    // console.log("【获取】===", strArr, strArr[9], strArr[7])
                    _this.getTableInfo(strArr[9], strArr[7])
                    _this.setData({
                        Biz_ID: strArr[9],
                        Table_ID: strArr[7]
                    })
                } else {
                    co.toast('您扫的不是码上点的二维码')
                }
            }
        })
    },
    //获取桌号对应订单信息
    getTableInfo: function (biz_id, tableId) {
        var param = {
            Biz_ID: biz_id,
            Table_ID: tableId
        }
        co.getShareApi('order/Omg/tableOrder', param, function (res) {
            console.log("【获取返回信息】===", res.data)
            if (res.code == 0) {    //此桌有订单时
                var obj = JSON.stringify(res.data)
                wx.navigateTo({
                    url: '/02local/07tableOrder/tableOrder?obj=' + obj,
                })
            } else{     //此桌无订单时
                wx.navigateTo({
                    url: '/02local/03foodInfo/foodInfo?Biz_ID=' + _this.data.Biz_ID + '&Table_ID=' + _this.data.Table_ID
                })
            }
        })
    }
})